<template>
    <div @click="triggerUpload" class="article-cover-uploader">
        <input type="file" @change="changeFile($event)" hidden ref="fileIptRef">
        <i v-if="!imgUrl" class="iconfont icon-jiahao"></i>
        <img v-else :src="imgUrl">
    </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import Messager from '@/utils/messager'
import axiosInstance from '@/utils/request'

const emits = defineEmits(['update:modelValue'])

const props = defineProps({
    
    modelValue: {
        type: String,
        default: '' // 默认图片地址
    },
    maxSize: {
        type: Number,
        default: 10 // 默认最大不超过5M
    },
    serverUrl: {
        type: String,
        default: 'http://119.23.61.24/api/static'
    }
})

const imgUrl = ref(props.modelValue)

const fileIptRef = ref(null)

function triggerUpload() {
    fileIptRef.value.click()
}

function changeFile(e) {
    let file = e.target.files[0]

    if (file.size / 1024 / 1024 > props.maxSize) {
        Messager.error('文件不能超过10M')
        return
    }

    // 执行文件上传
    let formData = new FormData()
    formData.append("mfile", file)
    formData.append("type", "article")
    let config = {
        headers: {
            'Content-Type': 'multipart/form-data',
            'a': 'b'
        }
    }
    axiosInstance.post('/file/uploadFile', formData, config).then(res => {
        console.log(res, '上传成功');
        imgUrl.value = props.serverUrl + res
        let img = new Image()
        img.src = imgUrl.value
        img.onload = () => {
            emits('update:modelValue', imgUrl.value)
        }
    })



}
</script>

<style lang="scss" scoped>
.article-cover-uploader {
    width: 360px;
    height: 180px;
    border: 1px dashed #409eff;
    border-radius: 5px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    overflow: hidden;
    img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        overflow: hidden;
    }
}

i.icon-jiahao {
    color: #409eff;
    font-size: 36px;
}
</style>